// Definition for a Node.
function Node(val, neighbors) {
  this.val = val === undefined ? 0 : val;
  this.neighbors = neighbors === undefined ? [] : neighbors;
};

function createGraph(list) {
  if(list.length == 0) return null;
  if(list.length == 1 && list[0].length === 0) return [null];
  let nodeList = [];
  for(let i = 1; i <= list.length; i++) {
    let node = new Node(i, []);
    nodeList.push(node);
  }
  for(let i = 0; i < nodeList.length; i++) {
    for(let j = 0; j < list[i].length; j++) {
      nodeList[i].neighbors.push(nodeList[list[i][j] - 1]);
    }
  }
  return nodeList[0];
}

/**
 * @param {Node} node
 * @return {Node}
 */
var cloneGraph = function (node) {
  node = createGraph(node);
  if(node == null)
    return null;
  if(node.neighbors.length == 0)
    return new Node(1, []);
  let visited = new Array(101).fill(false), queue = [node], result = new Array(101);
  for(let i = 0; i < result.length; i++) {
    let tNode = new Node(i + 1, []);
    result[i] = tNode;
  }
  // console.log("result", result);
  while(queue.length) {
    // 从队列中取出一个节点
    let tempNode = queue[0];
    // 出队
    queue.splice(0, 1);
    // 访问节点的值设为true
    visited[tempNode.val - 1] = true;
    for(let i = 0; i < tempNode.neighbors.length; i++) {
      result[tempNode.val - 1].neighbors.push(result[tempNode.neighbors[i].val - 1]);
      if(!visited[tempNode.neighbors[i].val - 1] && queue.indexOf(tempNode.neighbors[i]) == -1) {
        queue.push(tempNode.neighbors[i]);
      }
    }
  }
  // console.log(result[0], result[1], result[2], result[3])
  return result[0];
};
let adjList = [
  [2, 4],
  [1, 3],
  [2, 4],
  [1, 3]
];
console.log(cloneGraph(adjList));
adjList = [
  []
];
console.log(cloneGraph(adjList));
adjList = [];
console.log(cloneGraph(adjList));
adjList = [
  [2],
  [1]
];
console.log(cloneGraph(adjList));
